from google.appengine.ext import webapp, db
from google.appengine.ext.webapp.util import run_wsgi_app 
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch

import os, logging
from base_request import *

from urllib import urlencode

def debug_mode():
	return os.environ.get('SERVER_SOFTWARE','').lower().startswith('devel')
HOST = 'http://localhost:8080' if debug_mode() else 'http://bpic.appspot.com'

class Token(db.Model):  
	token = db.StringProperty()

class MainHandler(webapp.RequestHandler):
  def get(self):
    self.response.out.write(template.render('index.html',{'hostname': HOST})) 
	
	
class GAuth(BaseRequestHandler):
	def get(self,token = None):
		if token is None:
			def invalid(tok):
				r = urlfetch.fetch('https://www.google.com/accounts/AuthSubTokenInfo', headers = {'Authorization' : 'AuthSub token="'+tok+'"'})
				logging.debug(r.status_code)
				if r.status_code == 200:
					logging.debug(r.headers)					
					logging.debug(r.content)
				return False
			t = Token.get_by_key_name(self.user.email())			
			if t is None or invalid(t.token):
				self.seeother('https://www.google.com/accounts/AuthSubRequest?'+
					urlencode([('next',HOST+'/gauth'),
							   ('scope','http://www.blogger.com/feeds/ http://picasaweb.google.com/data'),
							   ('session','1'),
							   ('secure','1')]))
			else:
				self.response.out.write(t.token)
		else:
			t = Token.get_by_key_name(self.user.email())
			if t is None:
				t = Token(key_name  = self.user.email())
			t.token = token
			t.put()


		
if __name__ == '__main__':
	run_wsgi_app(webapp.WSGIApplication([('/', MainHandler),
										 ('/gauth', GAuth)
										 
										], debug=True))
